<template>
  <div id="container"
       class="app-map-wrapper">
    <div class="input-card">
      <input id="setFitView" type="button" class="btn" value="地图自适应显示" />
    </div>
    <div class="cameraInfoList" id="cameraInfoList" v-if="isCameraInfoListShow">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>点位信息</span>
        </div>
        <div v-for="(item,index) in cameraData" :key="index" class="text item">
          <label @click="cameraClickEvt(item.id)" v-if="cameraData.length > 0">
            <input type="radio" name="myRadio">{{item.no}}
          </label>
        </div>
      </el-card>
    </div>
    <div v-if="mapCompleteStatus" class="map-tree">
      <el-tree class="tree-detail" :data="treeData" node-key="id" :default-expanded-keys="defaultExdKeys" :props="treeProps"
        :expand-on-click-node="true"
        @node-click="handleNodeClick">
      </el-tree>
    </div>
    <iframe width="0" height="0" id="url" :src="url"></iframe>
  </div>
</template>
<script>
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {getMapLocationDown} from '@/http/AppApi'
import {getCameraPointpositionList, getVideo, getMapPoint} from '@/http/cameraApi'
import onlineBlot from '@/assets/img/onlineBlot.svg'
import breakdownBlot from '@/assets/img/breakdownBlot.svg'
export default {
  name: 'show-map',
  props: {},
  data () {
    return {
      AMapUI: null,
      AMap: null,
      map: null,
      marker: null,
      url: '',
      IsetCenter: true,
      mapCompleteStatus: false,
      isCameraInfoListShow: false,
      mapCenter: '',
      currentGridIds: [],
      infos: [],
      polygon: [],
      treeData: [],
      cameraData: [],
      treeProps: {
        label: 'name',
        children: 'children'
      },
      zoom: '',
      citySetTimes: 0,
      gridSetTimes: 0,
      villageSetTimes: 0,
      townsSetTimes: 0,
      levelNameArr: [
        'citySetTimes', 'gridSetTimes', 'villageSetTimes', 'townsSetTimes'
      ],
      gridZoom: {
        '06': 14.1, '05': 12.13, '04': 10.8, '03': 9.5
      }
    }
  },
  computed: {
    defaultExdKeys: function () {
      if (this.treeData && this.treeData instanceof Array && this.treeData.length > 0) {
        let firstNode = this.treeData[0]
        return [firstNode.id]
      }
    }
  },
  components: {},
  watch: {},
  mounted () {
    this.init()
    this.getAllPosition()
    this.cameraInfoListHide()
  },
  methods: {
    // 点击空白处点位信息列表小时
    cameraInfoListHide () {
      document.addEventListener('mouseup', (e) => {
        var _con = document.getElementById('cameraInfoList')
        if (_con) {
          if (!_con.contains(e.target)) {
            this.isCameraInfoListShow = false
          }
        }
      })
    },
    cameraClickEvt (id) {
      if (id) {
        let m = this
        getMapPoint(id).then(resp => {
          if (resp.code && resp.code === '200') {
            let resData = resp.data
            if (resData.longitude && resData.latitude && resData.latitude !== '' && resData.longitude !== '' && resData.latitude !== null && resData.longitude !== null) {
              m.map.setCenter([resData.longitude, resData.latitude])
              m.map.setZoom(17)
            }
          } else {
            m.$message({
              type: 'info',
              message: resp.message
            })
          }
        })
      } else {
        return ''
      }
    },
    createMarker (data) {
      if (data.length > 0) {
        var m = this
        var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)})
        for (let j in data) {
          getMapPoint(data[j].id).then(resp => {
            if (resp.code && resp.code === '200') {
              let resData = resp.data
              if (resData.longitude && resData.latitude && resData.latitude !== '' && resData.longitude !== '' && resData.latitude !== null && resData.longitude !== null) {
                let latLag = [resData.longitude, resData.latitude]
                let marker = new AMap.Marker({
                  icon: resData.cameraInfo.isOnline === '0' ? breakdownBlot : onlineBlot,
                  position: latLag
                })
                marker.no = resData.no
                marker.lnglats = resData.latLag
                marker.name = resData.cameraInfo.name === '' ? '无点位信息' : resData.cameraInfo.name
                m.map.add(marker)
                marker.on('click', m.markerClickEvt)
                // 鼠标悬浮点位信息窗口显示 infoWindow实例
                marker.on('mouseover', function (e) {
                  infoWindow.setContent(e.target.name)
                  infoWindow.open(m.map, e.target.getPosition())
                })
              } else {
                return ''
              }
            } else {
              return ''
            }
          })
        }
        AMap.event.addDomListener(document.getElementById('setFitView'), 'click', function () {
          m.map.setFitView()
        })
      } else {
        return ''
      }
    },
    init () {
      this.AMapUI = window.AMapUI
      this.AMap = window.AMap
      let mapConfig = {
        zoom: 13,
        viewMode: '3D',
        pitch: 40,
        cityName: '信阳',
        center: [114.091104, 32.148489]
      }
      this.map = new AMap.Map('container', mapConfig)
      this.map.on('complete', this.mapLoadComplete)
    },
    addUIs () {
      let map = this.map
      this.AMapUI.loadUI(['control/BasicControl'], function (BasicControl) {
        map.addControl(new BasicControl.LayerSwitcher({
          position: 'lt'
        }))
      })
    },
    mapLoadComplete () {
      this.mapCompleteStatus = true
      this.mapCenter = this.map.getCenter()
      this.map.setCenter([114.064496, 32.344488])
      this.map.setZoom(10.8)
      this.map.panBy(-50, -220)
      this.map.on('zoomend', this.mapZoomEnd)
      this.getTreeData()
    },
    // 地图鼠标滚动事件（结束时状态）
    mapZoomEnd () {
      this.IsetCenter = false
      let currentZoom = this.map.getZoom()
      let levelName = ''
      let level = ''
      if (currentZoom < 10.8) { // 市级
        levelName = 'city'
        level = '03'
      } else if (currentZoom >= 10.8 && currentZoom < 12.13) { // 区县
        levelName = 'towns'
        level = '04'
      } else if (currentZoom >= 12.13 && currentZoom < 14.1) { // 乡镇
        levelName = 'village'
        level = '05'
      } else if (currentZoom >= 14.1) { // 村社区
        levelName = 'grid'
        level = '06'
      } else {
        return ''
      }
      this.mapZoomChangeFun(levelName, level)
    },
    // 地图缩放级别变化对应信息封装
    mapZoomChangeFun (levelName, level) {
      if (levelName === '' || level === '') return ''
      let variateName = levelName + 'SetTimes'
      for (const key in this.levelNameArr) {
        if (variateName === this.levelNameArr[key]) continue
        let name = this.levelNameArr[key]
        this[name] = 0
      }
      this[variateName] += 1
      if (this[variateName] === 1) {
        console.log(levelName + '范围')
        this.gridMapLevelChange(level)
      }
    },
    gridMapLevelChange (level) {
      let treeData = this.treeData
      let levelCode = ''
      for (const key in treeData) {
        if (treeData.hasOwnProperty(key)) {
          levelCode = treeData[key].levelCode
          break
        }
      }
      // 如果待加载区域已经超出当前网格数据最高层级 return  不做加载
      if (levelCode !== '' && parseInt(level) < parseInt(levelCode)) return ''
      this.map.remove(this.polygon)
      this.map.remove(this.infos)
      this.polygon = []
      this.currentGridIds = []
      this.recursion(treeData, level)
    },
    // 递归加载地图不同层级网格区域
    recursion (treeData, level) {
      for (const key in treeData) {
        if (treeData.hasOwnProperty(key)) {
          if (level === treeData[key].levelCode) {
            this.currentGridIds.push(treeData[key].id)
            this.loadMapFun(treeData[key].id)
          } else {
            if (treeData[key].children) {
              let childNodes = treeData[key].children
              this.recursion(childNodes, level)
            }
          }
        }
      }
    },
    // 画网格
    createTarget (p) {
      if (p) {
        if (this.currentGridIds.indexOf(p.targetId) > -1) {
          if (this.IsetCenter) {
            this.map.setCenter([p.longitude, p.latitude])
          }
          return ''
        }
        let poly = {}
        if (p.mapColor) {
          poly.fillColor = p.mapColor
          poly.strokeColor = p.mapColor
        }
        if (p.mapArea) {
          poly.path = JSON.parse(p.mapArea)
          let polygon = new AMap.Polygon(poly)
          this.polygon.push(polygon)
          this.map.add(polygon)
        }
      }
    },
    loadMapFun (id) {
      let m = this
      this.loadGridMap(id).then(function (data) {
        for (const j in data) {
          if (data.hasOwnProperty(j)) {
            m.createTarget(data[j])
          }
        }
      }).catch(function (reason, data) {
        console.log(reason)
      })
    },
    // 利用promise处理异步加载
    loadGridMap (id) {
      var promise = new Promise(function (resolve, reject) {
        getMapLocationDown(id).then(resp => {
          if (resp.code && resp.code === '200') {
            resolve(resp.data)
          } else {
            reject(resp.message)
          }
        })
      })
      return promise
    },
    getTreeData () {
      this.IsetCenter = true
      let tree = getUserGridTree()
      this.currentGridIds = []
      let m = this
      if (tree && tree instanceof Array) {
        m.treeData = tree
        if (tree.length > 0) {
          for (const key in tree) {
            if (tree.hasOwnProperty(key)) {
              m.currentGridIds.push(tree[key].id)
              let level = tree[key].levelCode
              m.map.setZoom(m.gridZoom[level])
              m.loadMapFun(tree[key].id)
            }
          }
        }
      }
    },
    getAllPosition (id) {
      let m = this
      getCameraPointpositionList(id).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.cameraData = data
          m.createMarker(data)
        }
      })
    },
    handleNodeClick (data) {
      this.isCameraInfoListShow = true
      this.cameraInfoListHide()
      this.getAllPosition(data.id)
    },
    async markerClickEvt (e) {
      this.map.setCenter(e.target.lnglats)
      let cameraId = e.target.no
      let res = await getVideo({ indexCode: cameraId }).then(resp => {
        return resp
      })
      let data = res.data
      let param =
        'hikvideoclient://ReqType:' +
        'PlayReal' +
        ';' +
        'VersionTag:artemis' +
        ';' +
        'SvrIp:' +
        '125.45.145.172' +
        ';' +
        'SvrPort:' +
        '444' +
        ';' +
        'Appkey:' +
        data.appkey +
        ';' +
        'AppSecret:' +
        data.appSecret +
        ';' +
        'time:' +
        data.time +
        ';' +
        'TimeSecret:' +
        data.timesecret +
        ';' +
        'httpsflag:' +
        '1' +
        ';' +
        'CamList:' +
        cameraId +
        ';' +
        'wndCount:' +
        '1' +
        ';'
      this.url = param
    }
  }
}
</script>
<style scoped>
.app-map-wrapper {
  position: relative;
  height: 700px;
}
.app-map-wrapper .map-tree {
  position: absolute;
  top: 70px;
  top: 30px;
  left: 30px;
  height: 500px;
  width: 200px;
  overflow-y: scroll;
  overflow-x: hidden;
  z-index: 99999;
}
.map-tree::-webkit-scrollbar {
  display: none;
}
.cameraInfoList {
  position: absolute;
  top: 30px;
  left: 240px;
  height: 500px;
  width: 220px;
  overflow-y: scroll;
  overflow-x: hidden;
  z-index: 99991;
  font-size: 14px;
}
.cameraInfoList .item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card {
  width: 100%;
}
.cameraInfoList::-webkit-scrollbar {
  display: none;
}
.input-card {
  position: absolute;
  bottom: 126px;
  right: 58px;
  z-index: 99999;
}
#setFitView {
  border: none;
  background-color: rgb(206, 212, 212);
  color: black;
  height: 30px;
  line-height: 30px;
  border-radius: 15px;
  padding: 0 10px;
}
p.my-desc {
  margin: 5px 0;
  line-height: 150%;
}
</style>
